package com.yanfei.zero.domain.user.model.perms;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import com.ververica.cdc.connectors.shaded.org.apache.kafka.common.errors.ApiException;
import com.yanfei.zero.application.handler.perms.ICmResourceService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
 * 权限拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {

	@Autowired
    private ICmResourceService cmResourceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是静态资源，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取请求的最佳匹配路径，这里的意思就是我之前数据演示的/API/user/test/{id}路径参数
        // 如果用uri判断的话就是/API/user/test/100，就和路径参数匹配不上了，所以要用这种方式获得
        String pattern = (String)request.getAttribute(
                HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        // 将请求方式（GET、POST等）和请求路径用 : 拼接起来，等下好进行判断。最终拼成字符串的就像这样：DELETE:/API/user
        String path = request.getMethod() + ":" + pattern;
        
//        Set<String> userPaths = cmResourceService.getPathsByUserId("userId");
//        
//        // 判断该接口是不是属于当前用户的权限范围，如果不是，则代表该接口用户没有权限
//        if (!userPaths.contains(path)) {
//            throw new ApiException(HttpStatus.FORBIDDEN.toString());
//        }
        // 有权限就放行
        return true;
    }
}